package com.ruoyi.business.service.impl;

import com.ruoyi.business.service.IProcessService;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

@Service
public class ProcessServiceImpl implements IProcessService {

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;

    @Override
    public Deployment deploy(String filePast) throws FileNotFoundException {
        Deployment deploy = null;
        if (filePast.endsWith("zip")){
            ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(filePast));
            deploy = repositoryService.createDeployment()
                    .addZipInputStream(zipInputStream)
                    .deploy();
        }else if (filePast.endsWith("bpmn")){
            deploy = repositoryService.createDeployment()
                    .addInputStream(filePast,new FileInputStream(filePast))
                    .deploy();
        }
        return deploy;
    }

    @Override
    public ProcessDefinition getProcessDefinitionByDeploymentId(String deploymentId) {
        return repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
    }

    @Override
    public InputStream getBpmnInputStream(String deploymentId) {
        //  获取流程定义 获取到bpmn的文件名
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
        //  传入部署id,bpmn的文件名.可以获取到bpmn输入流信息
        return repositoryService.getResourceAsStream(deploymentId,processDefinition.getResourceName());
    }

    @Override
    public InputStream getProcessImage(String deploymentId) {
        //  获取流程定义ID
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
        //  获取bpmnModel
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
        //  定义绘制图形对象
        DefaultProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
        //  第一个参数: bpmnModel 第二个参数: 需要高亮的节点集合 第三个参数: 需要高亮连线集合
        InputStream inputStream = processDiagramGenerator.generateDiagram(bpmnModel, Collections.EMPTY_LIST, Collections.EMPTY_LIST, "宋体", "宋体", "宋体");
        return inputStream;
    }

    @Override
    public ProcessInstance startProcessInstance(String definitionKey, String businessKey, Map<String, Object> variables) {
        return runtimeService.startProcessInstanceByKey(definitionKey,businessKey,variables);
    }

    @Override
    public Task getTaskByProcessInstanceId(String processInstanceId) {
        return taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
    }

    @Override
    public void addCandidateUser(Task task, Long userId) {
        taskService.addCandidateUser(task.getId(),String.valueOf(userId));
    }

    @Override
    public InputStream getProcessImgByInstanceId(String instanceId) {
        //  获取历史流程实例对象
        HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(instanceId).singleResult();
        //  获取bpmnModel 主要描述节点 连接的信息
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
        //  定义绘制图形对象
        DefaultProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
        //  我们当前运行时 根据流程实例id 判断流程是否已经结束了
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(instanceId).singleResult();
        List<String> activeActivityIds = null;
        if (instance!=null){
            //  流程还没有结束
            //  获取目前正在流转节点
            activeActivityIds = runtimeService.getActiveActivityIds(processInstance.getId());
        }else{
            activeActivityIds = Collections.EMPTY_LIST;
        }
        //  第一个参数: bpmnModel 第二个参数: 需要高亮的节点集合 第三个参数: 需要高亮连线集合
        InputStream inputStream = processDiagramGenerator.generateDiagram(
                bpmnModel,
                activeActivityIds,
                Collections.EMPTY_LIST,
                "宋体", "宋体", "宋体");
        return inputStream;
    }

    @Override
    public void deleteProcessInstance(String instanceId) {
        //  执行此方法后未审批的任务 act_ru_task 会被删除，
        //  流程历史 act_hi_taskinst 不会被删除，并且流程历史的状态为finished完成
        runtimeService.deleteProcessInstance(instanceId, "撤销申请");
    }

    @Override
    public Long getTodoTaskCount(String definitionKey, String userId) {
        //  通过流程定义key 获取候选人 待办条数
        return taskService.createTaskQuery().processDefinitionKey(definitionKey).taskCandidateUser(userId).count();
    }

    @Override
    public List<Task> selectTodoList(String definitionKey, String userId, Integer startNum, Integer pageSize) {
        return taskService.createTaskQuery()
                .processDefinitionKey(definitionKey)
                .taskCandidateUser(userId)
                .orderByTaskCreateTime()
                .desc()
                .listPage(startNum, pageSize);
    }

    @Override
    public ProcessInstance getProcessInstanceById(String processInstanceId) {
        return runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
    }

    @Override
    public Task getTaskByTaskId(String taskId) {
        return taskService.createTaskQuery().taskId(taskId).singleResult();
    }

    @Override
    public void claimAndComplete(Task task, String userId, Boolean auditStatus, String comment) {
        String commentStr = auditStatus?"[同意]":"[拒绝]";
        commentStr+=comment;
        //  1.给当前任务添加批注信息
        taskService.addComment(task.getId(), task.getProcessInstanceId(), commentStr);
        //  2.认领任务
        taskService.claim(task.getId(), userId);
        //  3.执行任务,把流程变量传入
//        Map<String,Object> variable = new HashMap<>();
//        variable.put(task.getTaskDefinitionKey(), auditStatus);//任务定义key作为key,true/false为value
//        taskService.complete(task.getId(),variable);
        //  第一次设置直接加入流程变量中, 第二次如果key名字相同,把流程变量覆盖
        taskService.setVariable(task.getId(),task.getTaskDefinitionKey(),auditStatus);
        taskService.complete(task.getId());
    }

    @Override
    public void claimAndComplete(Task task, String userId, String comment) {
        //  1.给当前任务添加批注信息
        taskService.addComment(task.getId(), task.getProcessInstanceId(), comment);
        //  2.认领任务
        taskService.claim(task.getId(), userId);
        //  3.完成任务
        taskService.complete(task.getId());
    }

    @Override
    public void setVariable(String taskId, String key, long value) {
        taskService.setVariable(taskId, key, value);
        //  runtimeService实际上并没有覆盖流程变量
        //runtimeService.setVariable(processInstanceId,key, value);
    }

    @Override
    public long getHistoricTaskCount(String definitionKey, String userId) {
        //  流程一执行,立马把节点存储到历史表中,运行时表也存储一份
        return historyService.createHistoricTaskInstanceQuery()
                .processDefinitionKey(definitionKey)
                .taskAssignee(userId)
                .finished()
                .count();
    }

    @Override
    public List<HistoricTaskInstance> selectHistoricTaskList(String definitionKey, String userId, Integer startNum, Integer pageSize) {
        return historyService.createHistoricTaskInstanceQuery()
                .processDefinitionKey(definitionKey)
                .taskAssignee(userId)
                .finished()
                .orderByHistoricTaskInstanceEndTime() // 按照任务完成的结束时间进行排序
                .asc()
                .listPage(startNum, pageSize);
    }

    @Override
    public HistoricProcessInstance getHistoricProcessInstanceById(String processInstanceId) {
        return historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
    }

    @Override
    public List<HistoricActivityInstance> selectHistoricActivityList(String instanceId) {
        List<HistoricActivityInstance> list = historyService.createHistoricActivityInstanceQuery()
                .activityType("userTask")
                .processInstanceId(instanceId)
                .finished()
                .orderByHistoricActivityInstanceEndTime()
                .asc().list();
        return list;
    }

    @Override
    public String getComment(String taskId) {
        //  用任务id找到任务备注
        List<Comment> taskComments = taskService.getTaskComments(taskId);
        if (taskComments!=null && taskComments.size()>0){
            //  取第一条备注 获取所有信息
            return taskComments.get(0).getFullMessage();
        }else {
            return "";
        }
    }
}
